package cz.af.portletExams.backend.rest.converter;

import cz.af.portletExams.backend.rest.dto.ExamsForSubject;
import cz.af.portletExams.model.Exam;
import org.jdom.Element;
import org.jdom.Namespace;
import org.joda.time.LocalDateTime;

import java.util.ArrayList;
import java.util.List;

public class ExamsForSubjectsConverter extends GenericExamModelConverter<ExamsForSubject> {

    @Override
    protected ExamsForSubject convertToObject(Element rootElement) {
        final ExamsForSubject examsForSubject = new ExamsForSubject();
        final List<Exam> exams = new ArrayList<Exam>();
        examsForSubject.setExams(exams);

        final Namespace atomNamespace = rootElement.getNamespace();
        final Namespace defaultNamespace = rootElement.getNamespace("");
        final Namespace xlinkNamespace = rootElement.getNamespace("xlink");


        final List<Element> entries = rootElement.getChildren("entry", atomNamespace);
        for (Element element : entries) {
            final Exam exam = new Exam();

            final String[] split = element.getChild("id", atomNamespace).getText().split(":");
            exam.setId(split[split.length - 1]);

            final Element content = element.getChild("content", atomNamespace);

            exam.setCapacity(Integer.parseInt(content.getChild("capacity", defaultNamespace).getText()));
            exam.setOccupied(Integer.parseInt(content.getChild("occupied", defaultNamespace).getText()));

            final String startDate = content.getChild("startDate", defaultNamespace).getText();
            final LocalDateTime localDateTime = LocalDateTime.parse(startDate);
            exam.setDate(localDateTime);

            final String course = content.getChild("course", defaultNamespace).getAttribute("href", xlinkNamespace).getValue();
            final String[] strings = course.split("/");
            exam.setSubjectId(strings[1]);

            exams.add(exam);
        }
        return examsForSubject;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return ExamsForSubject.class == clazz;
    }
}
